package com.guaoran.activity.notify;

import com.guaoran.activity.dal.entitys.ActDrawNum;
import com.guaoran.activity.dal.persistence.ActDrawNumMapper;
import com.guaoran.common.utils.JsonUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.kafka.listener.MessageListener;
import org.springframework.stereotype.Service;

/**
 * 注册监听
 */
@Service
public class RegistryListener implements MessageListener<Integer, String> {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    ActDrawNumMapper actDrawNumMapper;

    @Override
    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
        Object[] userBean = null;
        try {
            //幂等校验
            String jsonStr = integerStringConsumerRecord.value();
            logger.info("message{}",jsonStr);
            userBean = jsonStr.split("#");
            ActDrawNum actDrawNum = new ActDrawNum();
            actDrawNum.setName(String.valueOf(userBean[1]));
            actDrawNum.setNowNumber(0);
            actDrawNum.setUid(Integer.parseInt(String.valueOf(userBean[0])));
            actDrawNum.setMaxNumber(1);
            actDrawNumMapper.inputDrawNumber(actDrawNum);
        } catch (DuplicateKeyException e) {
            //已经存在用户的抽奖资格记录，则累加抽奖机会
            actDrawNumMapper.updateMaxNumber(Integer.parseInt(String.valueOf(userBean[0])));
        } catch (Exception e) {
            throw new RuntimeException("消息处理异常:" + e);
        }
    }
}
